"""
Verify that workspace_id is required for POST /api/v1/hiagent/personal-agents
Test cases:
1. Create agent without workspace_id - should fail with 422 error
2. Create agent with workspace_id - should succeed
3. Service layer validation test
"""
import sys
import os

# Add project root to path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import requests
import json
from src.llm.hiagent_app.utils.api_client import HiAgentConfig

def test_create_agent_without_workspace_id():
    """Test case 1: Create agent without workspace_id should fail"""
    print("\n" + "="*60)
    print("TEST 1: Create agent WITHOUT workspace_id")
    print("="*60)

    url = "http://localhost:8000/api/v1/hiagent/personal-agents"

    # Request body without workspace_id
    data = {
        "name": "Test Agent No Workspace",
        "description": "Test agent without workspace_id",
        "app_type": "Chat"
    }

    print(f"\nRequest: POST {url}")
    print(f"Body: {json.dumps(data, indent=2, ensure_ascii=False)}")

    try:
        response = requests.post(url, json=data)
        print(f"\nResponse Status: {response.status_code}")
        print(f"Response Body: {json.dumps(response.json(), indent=2, ensure_ascii=False)}")

        if response.status_code == 422:
            print("\n✓ PASS: API correctly rejects request without workspace_id")
            return True
        else:
            print(f"\n✗ FAIL: API should return 422 but got {response.status_code}")
            return False

    except Exception as e:
        print(f"\n✗ FAIL: Exception occurred: {str(e)}")
        return False


def test_create_agent_with_workspace_id():
    """Test case 2: Create agent with workspace_id should succeed"""
    print("\n" + "="*60)
    print("TEST 2: Create agent WITH workspace_id")
    print("="*60)

    # Get workspace_id from config
    config = HiAgentConfig()
    workspace_id = config.DEFAULT_WORKSPACE_ID

    if not workspace_id:
        print("\n✗ FAIL: DEFAULT_WORKSPACE_ID not configured")
        return False

    url = "http://localhost:8000/api/v1/hiagent/personal-agents"

    # Request body with workspace_id
    data = {
        "name": f"Test Agent With Workspace {os.urandom(4).hex()}",  # Random name to avoid duplicates
        "description": "Test agent with workspace_id",
        "workspace_id": workspace_id,
        "app_type": "Chat"
    }

    print(f"\nRequest: POST {url}")
    print(f"Body: {json.dumps(data, indent=2, ensure_ascii=False)}")

    try:
        response = requests.post(url, json=data)
        print(f"\nResponse Status: {response.status_code}")
        result = response.json()
        print(f"Response Body: {json.dumps(result, indent=2, ensure_ascii=False)}")

        if response.status_code == 200:
            if result.get("success"):
                app_id = result.get("data", {}).get("app_id")
                print(f"\n✓ PASS: Agent created successfully with app_id: {app_id}")

                # Clean up: try to delete the created agent
                try:
                    delete_url = f"http://localhost:8000/api/v1/hiagent/personal-agents/{app_id}"
                    delete_response = requests.delete(
                        delete_url,
                        params={"workspace_id": workspace_id}
                    )
                    if delete_response.status_code == 200:
                        print(f"✓ Cleanup: Agent deleted successfully")
                except Exception as cleanup_error:
                    print(f"⚠ Cleanup warning: Could not delete agent: {cleanup_error}")

                return True
            else:
                print(f"\n✗ FAIL: Response success=False")
                return False
        else:
            print(f"\n✗ FAIL: Expected 200 but got {response.status_code}")
            return False

    except Exception as e:
        print(f"\n✗ FAIL: Exception occurred: {str(e)}")
        import traceback
        traceback.print_exc()
        return False


def test_service_layer():
    """Test case 3: Test service layer validation"""
    print("\n" + "="*60)
    print("TEST 3: Test service layer validation")
    print("="*60)

    try:
        from src.llm.hiagent_app.services.personal_agent_service import PersonalAgentService
        from src.llm.hiagent_app.models.hiagent_models import AppType

        service = PersonalAgentService()

        # Try to call without workspace_id (passing None)
        print("\nCalling create_personal_agent with workspace_id=None...")

        try:
            app_id = service.create_personal_agent(
                name="Test Agent",
                description="Test description",
                app_type=AppType.CHAT,
                workspace_id=None
            )
            print("\n✗ FAIL: Service should raise ValueError but didn't")
            return False
        except ValueError as e:
            print(f"\nCaught expected ValueError: {str(e)}")
            if "workspace_id is required" in str(e):
                print("✓ PASS: Service correctly validates workspace_id")
                return True
            else:
                print("✗ FAIL: Wrong error message")
                return False

    except Exception as e:
        print(f"\n✗ FAIL: Exception occurred: {str(e)}")
        import traceback
        traceback.print_exc()
        return False


if __name__ == "__main__":
    print("\n" + "="*60)
    print("CREATE AGENT - WORKSPACE_ID REQUIRED VERIFICATION")
    print("="*60)

    results = []

    # Test 1: Create agent without workspace_id
    results.append(("Create agent without workspace_id", test_create_agent_without_workspace_id()))

    # Test 2: Create agent with workspace_id
    results.append(("Create agent with workspace_id", test_create_agent_with_workspace_id()))

    # Test 3: Service layer validation
    results.append(("Service layer validation", test_service_layer()))

    # Summary
    print("\n" + "="*60)
    print("SUMMARY")
    print("="*60)

    passed = sum(1 for _, result in results if result)
    total = len(results)

    for name, result in results:
        status = "✓ PASS" if result else "✗ FAIL"
        print(f"{status}: {name}")

    print(f"\nTotal: {passed}/{total} tests passed")

    if passed == total:
        print("\n✓ All tests passed!")
        sys.exit(0)
    else:
        print("\n✗ Some tests failed!")
        sys.exit(1)
